//
//  QDMetroCodeTableViewController.m
//  QDMetroClient
//
//  Created by YueWen on 2018/12/28.
//  Copyright © 2018 YueWen. All rights reserved.
//

#import "QDMetroCodeTableViewController.h"
#import "JCBrightness.h"
#import "RITLSegmentBar.h"
#import "QDTabBarController.h"
#import "QDScreenShotAlertView.h"
#import "QDMetroCodeHeaderView.h"
#import "QDMetroErrorHeaderView.h"
#import "QDCodePopOverTableView.h"
#import "QDMetroCycleTableViewCell.h"
#import "RITLSystemSettingVisitor.h"
#import "QDCopygraphViewController.h"

#import <PopoverObjC/ASPopover.h>
#import <PopoverObjC/ASPopoverOption.h>

#import "QDBusCodeManager.h"
#import "QDMetroCodeManager.h"
#import "RITLQRCodeMaker.h"

#import "QDMetroClient-Swift.h"

/// 此界面需要 判断网络 - 蓝牙状态
@interface QDMetroCodeTableViewController ()
<
QDMetroErrorHeaderViewDelegate,
QDScreenShotAlertViewDelegate,
QDCodePopOverTableViewDelegate,
RITLSegmentBarDelegate,
QDCodeDataManager,
QDNoticeViewDelegate,
HeziBannerOpenActivePageDelegate
>

/// 出现异常的的headerView
@property (nonatomic, strong) QDMetroErrorHeaderView *errorHeaderView;
/// 导航栏右侧的popover的触发工具
@property (nonatomic, strong) ASPopover *itemPopover;
/// 导航栏右侧展示出的列表container
@property (nonatomic, strong) QDCodePopOverTableView *popOverView;
/// 模拟导航栏
@property (nonatomic, strong) UIView *titleView;
/// 导航栏右侧的按钮
@property (nonatomic, strong) UIButton *rightButton;
/// 选择地铁乘车码还是公交乘车码的segment
@property (nonatomic, strong) QDMetroCodeSegmentBar *segmentBar;
/// 避免计时器在viewDidLoad以及viewDidAppear中重复
@property (nonatomic, assign) BOOL requestInViewDidAppear;

/// 紧急公告的视图
@property (nonatomic, strong) QDNoticeView * noticeView;

// 数据逻辑控制
/// 公交车二维码
@property (nonatomic, strong) QDBusCodeManager *busCodeManager;
/// 地铁二维码
@property (nonatomic, strong) QDMetroCodeManager *metroCodeManager;
/// 当前的二维码的管理者
@property (nonatomic, weak) id <QDCodeManager> currentCodeManager;

/// 紧急公告
@property (nonatomic, copy)NSArray <NSString *> *notices;
/// 紧急公告的跳转链接
@property (nonatomic, copy)NSArray <NSString *> *noticesUrls;


@end

@implementation QDMetroCodeTableViewController

- (void)loadPropertysAtInitialization {    
    [super loadPropertysAtInitialization];
    
    self.hidesBottomBarWhenPushed = false;
    self.headerRefreshEnable = false;
    self.footerRefreshEnable = false;
    self.requestInViewDidAppear = false;
    self.imageUrls = @[];
    self.webUrls = @[];
    self.isMetro = true;//默认是
    self.servicePhone = @"053255770000";
}


- (void)registerTableViewCellsAndReusableView {
    [self.tableView registerClass:QDMetroCycleTableViewCell.class forCellReuseIdentifier:@"QDMetroCycleTableViewCell"];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    //面对尺寸小的机型，适当增加底部的inset
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, UIScreen.mainScreen.ritl_height < 600 ? 20 : 0, 0);
    self.tableView.scrollEnabled = isSmallerScreen();
    [self.tableView ritl_setContentInsetAdjustmentBehaviorToNeverBeforeiOS11Handler:^{
        self.automaticallyAdjustsScrollViewInsets = false;
    }];
    
    //背景颜色
    self.view.backgroundColor = RITLColorFromIntRBG(100, 181, 116);
    //创建二维码展示header
    [self buildCodeHeaderView];
    //默认设置为header
    self.tableView.tableHeaderView = self.errorHeaderView;
    
    /// 紧急公告
    self.noticeView = ({
        
        QDNoticeView *view = [QDNoticeView new];
        view.ritl_originX = 20;
        view.ritl_originY = 0;
        view.marqueeView.fadeWidth = 8;
        view.ritl_size = CGSizeMake(self.ritl_width - 40, 0);
        view.layer.cornerRadius = 4;
        view.clipsToBounds = true;
        view.imageView.image = @"mp_metro_notice_left".ritl_image;
        view.delegate = self;
        view.imageViewMarginLeft = 8;
        
        view;
    });

    // 追加模拟导航
    [self.view addSubview:self.titleView];
    [self.tableView addSubview:self.noticeView];
    
    // titleView的高度
    CGFloat titleViewHeight = RITL_DefaultNaviBarHeight + 40 - (isSmallerScreen() ? 18 : 0);
    
    [self.titleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.offset(0);
        make.height.mas_equalTo(titleViewHeight);
    }];
    
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.equalTo(self.titleView.mas_bottom);
    }];
    
    // 追加截屏通知中心
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(screenDidShot:) name:UIApplicationUserDidTakeScreenshotNotification object:nil];
    
    // 追加登陆通知
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(requestAllPayType) name:@"QDLoginCompleteNotificationName" object:nil];
    
    // 追加退出通知
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(requestAllPayType) name:@"QDLogoutCompleteNotificationName" object:nil];
    
    // 追加支付方式变化通知
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(requestAllPayType) name:@"QDPayTypeStatusDidChangedNotificationName" object:nil];
    
    // 接收退出前台
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(viewDidDisappear:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(viewDidDisappear:) name:UIApplicationWillResignActiveNotification object:nil];
    
    // 追加3D touch追加的响应
    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(actionWithShortItem) name:@"QDShortcutItemDidTapFromtTabNotificationName" object:nil];
    
    // 根据本地存储的 short item 数据设置默认
    self.isMetro = [[QDCodeSettingConfiguration codeSettingTypeForShortItemToOC] isEqualToString:@"qd_metro"];
    _currentCodeManager = self.isMetro ? self.metroCodeManager : self.busCodeManager;//设置默认
    
    // 设置segmentBar的UI,但是不启用回调
    [self.segmentBar selectedIndexWithIndex:self.isMetro ? 0 : 1 action:false];

    //请求所有的方式
    [self requestAllPayType];
    //请求广告位
    [self requestAdsAtMetroCodeController];
}



- (void)viewDidAppear:(BOOL)animated {
    
    [super viewDidAppear:animated];
    [JCBrightness graduallySetBrightness:1.0];
    //开启二维码刷新,用来避免viewDidLoad中的requestAllPayType重复请求
    if (self.requestInViewDidAppear) {
        self.currentCodeManager = self.currentCodeManager;
    }
    self.requestInViewDidAppear = true;
    //请求紧急公告
    [self requestUrgentNotices];
}



/// 根据3D touch响应进行操作
- (void)actionWithShortItem {
    
    self.isMetro = [[QDCodeSettingConfiguration codeSettingTypeForShortItemToOC] isEqualToString:@"qd_metro"];
    //消除3DTouch
    [QDCodeSettingConfiguration removeSettingForShortItem];
    //进行UI响应
    [self.segmentBar selectedIndexWithIndex:self.isMetro ? 0 : 1 action:false];
    //如果没有登陆
    if (!QDUserStatus.isLogin) {
        [self updateTableHeaderViewWithErrorType:QDMetroHeaderErrorTypeLoginStatus]; return;
    }
    
    //如果没有变化，不进行操作
    if ((self.isMetro && [self.currentCodeManager isEqual:self.metroCodeManager]) ||
        (!self.isMetro && [self.currentCodeManager isEqual:self.busCodeManager])) {
        return;
    }
    
    self.currentCodeManager = self.isMetro ? self.metroCodeManager : self.busCodeManager;
}


- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    [JCBrightness graduallyResumeBrightness];
}



- (void)viewDidDisappear:(BOOL)animated {
    
    [super viewDidDisappear:animated];
    [self.currentCodeManager resignFirstControl];
    if (!self.noticeView.marqueeView.isStopped && self.noticeView.marqueeView.isRunning){
        [self.noticeView.marqueeView pause];
    }
}


/// 创建展示二维码的header视图
- (void)buildCodeHeaderView {
    // 初始化存放二维码的header
    self.codeHeaderView = ({
        
        QDMetroCodeHeaderView *view = [QDMetroCodeHeaderView new];
        view.frame = CGRectMake(0, 0, self.ritl_width, 395 + QDAddtionMiddleDistance() + QDAddtionTopDistance());
        
        __weak typeof(self) weakSelf = self;
        //设置点击回调
        view.changeTypeHandler = ^{
            [weakSelf showPayTypePickerView];
        };
        
        view;
    });
    
    __weak typeof(self) weakSelf = self;
    self.codeHeaderView.codeImageView.userInteractionEnabled = true;
    [self.codeHeaderView.codeImageView addUIControlHandler:^(UIView * _Nonnull view) {
        [weakSelf.currentCodeManager reloadForce];//强制刷新
    }];
}



#pragma mark - Super
// 重写父类该方法，避免父类布局
- (void)makeTableViewConstraints {}
- (UIColor *)tableViewBackgroundColor { return RITLColorFromIntRBG(100, 181, 116); }
- (UIStatusBarStyle)preferredStatusBarStyle { return UIStatusBarStyleLightContent; }
#pragma mark - UINavigationBar
- (BOOL)nav_barHidden { return true; }
- (BOOL)nav_barShadowHidden { return true; }

#pragma mark - Action

/// rightButtonItem 点击响应的方法
- (void)rightButtonItemDidTap {
    
    CGFloat popHeight = [QDCodePopOverTableView heightForPopOverTableViewWithCount:self.currentCodeManager.titles.count];
    
    if (!_popOverView) {
        _popOverView = [[QDCodePopOverTableView alloc] initWithFrame:CGRectMake(0, 0, 122, popHeight)];
        _popOverView.delegate = self;
    }
    UIView *itemView = self.titleView;

    if (itemView) {

        [self.popOverView updateTitles:self.currentCodeManager.titles images:self.currentCodeManager.imageNames];
        
        //获得point
        CGRect showRect = [itemView convertRect:self.rightButton.frame toView:self.view];
        CGPoint showPoint = CGPointMake(CGRectGetMinX(showRect) + CGRectGetWidth(showRect) / 2.0 + 7, CGRectGetMidY(showRect) + 18);
        
        [self.itemPopover show:self.popOverView atPoint:showPoint]; // above,
    }
}



#pragma mark - CodeManager

- (void)setCurrentCodeManager:(id<QDCodeManager>)currentCodeManager {
    
    //更新状态进行拦截
    [_currentCodeManager resignFirstControl];

    QDMetroHeaderErrorType errorType = self.errorHeaderView.errorType;
    // 如果不是没有登陆状态并且也不是NFC
    if (errorType != QDMetroHeaderErrorTypeLoginStatus &&
        errorType != QDMetroHeaderErrorTypeNFC){
        
        self.tableView.tableHeaderView = self.errorHeaderView;
        [self.errorHeaderView updateHeaderViewWithType:QDMetroHeaderErrorTypeNone];
        [self.tableView bringSubviewToFront:self.noticeView];// 紧急公告放在最前
    }
    
    /// 展示公交提醒
    _currentCodeManager = currentCodeManager;
    _currentCodeManager.channelType = self.paytypePickView.channelType;
    _currentCodeManager.codeDelegate = self;
    
    // 如果是公交
    if ([currentCodeManager isEqual:self.busCodeManager]) {
        if (self.errorHeaderView.errorType == QDMetroHeaderErrorTypeOutBluetooth || self.errorHeaderView.errorType == QDMetroHeaderErrorTypeNFC){//无视蓝牙
            [self updateTableHeaderViewWithErrorType:QDMetroHeaderErrorTypeNone];
        }
        
        if (self.errorHeaderView.errorType == QDMetroHeaderErrorTypeNone) {
            [currentCodeManager becomeFirstControl];
        }
        return;
    }
    
    
    //地铁 - 如果是异常状态，则不进行请求
    if (self.errorHeaderView.errorType == QDMetroHeaderErrorTypeNone) {
        [currentCodeManager becomeFirstControl];
    }
}


- (void)setCurrentCodeManagerWithIsMetro:(BOOL)isMetro {
    self.currentCodeManager = isMetro ? self.metroCodeManager : self.busCodeManager;
}


- (void)setCodeManagerHasChannelTypes:(BOOL)hasChannelTypes {
    //
    self.metroCodeManager.hasChannel = hasChannelTypes;
    self.busCodeManager.hasChannel = hasChannelTypes;
}


- (QDBusCodeManager *)busCodeManager {
    if (!_busCodeManager) {
        _busCodeManager = QDBusCodeManager.new;
    }
    return _busCodeManager;
}


- (QDMetroCodeManager *)metroCodeManager {
    if (!_metroCodeManager) {
        _metroCodeManager = QDMetroCodeManager.new;
    }
    return _metroCodeManager;
}



#pragma mark - TableCodeHeaderView
/// 显示当前的二维码
- (void)updateTableHeaderViewWithCodeString:(NSString *)code orImage:(UIImage *)codeImage{
    
    /// 记录没有当前错误状态
    [self.errorHeaderView updateHeaderViewWithType:QDMetroHeaderErrorTypeNone];
    
    // 修改状态展示
    if(![self.tableView.tableHeaderView isEqual:self.codeHeaderView]){//如果不是显示在当前界面,更新

        self.tableView.tableHeaderView = self.codeHeaderView;
        [self.tableView bringSubviewToFront:self.noticeView]; //紧急公告放在最前
    }
    
    self.codeHeaderView.codeImageView.image = codeImage ? codeImage : [RITLQRCodeMaker makeQRCodeWithValue:code size:202];
}



/// 根据 错误类型 修改错误显示
- (void)updateTableHeaderViewWithErrorType:(QDMetroHeaderErrorType)type {
    
    // 停止二维码请求
    [self.currentCodeManager cancleRequest];
    
    // 修改Error状态展示
    if(![self.tableView.tableHeaderView isEqual:self.errorHeaderView]){//如果不是显示在当前界面,更新
        self.tableView.tableHeaderView = self.errorHeaderView;
    }
    
    [self.errorHeaderView updateHeaderViewWithType:type];
}


#pragma mark - <QDNoticeViewDelegate>
/// 点击
- (void)noticeViewDidClickWithView:(QDNoticeView *)view {
    
    [self pushToShareWebViewControllerWithUrl:self.noticesUrls.firstObject
                                   shareTitle:self.notices.firstObject
                                shareImageUrl:nil
                                    shareDesc:nil
                                    autoTitle:false
                                        title:@"详情"
                                           id:nil
                                      qdmetro:false];
}


#pragma mark - NotificationCenter

/// 截屏了
- (void)screenDidShot:(NSNotification *)notification {
    
    /// 如果是当前在最上方
    if (![QDTabBarController.sharedInstance.visibleViewController isEqual:self]) { return; }
    /// 如果不是二维码，则不进行
    if (![self.tableView.tableHeaderView isEqual:self.codeHeaderView]){ return; }
    
    NSString *title = [self.currentCodeManager isEqual:self.metroCodeManager] ? @"地铁乘车码实时刷新，截图中的二维码无法使用哦~" : @"公交乘车码已刷新，截图中的二维码无法使用哦~";
    [QDScreenShotAlertView showAndBecomeDelegate:self title:title];
    [self.currentCodeManager reloadForce];//强制刷新
}

#pragma mark - <QDCodeDataManager>

- (void)codeManager:(id<QDCodeManager>)codeManager codeString:(nonnull NSString *)code info:(nullable NSDictionary *)info image:(nullable UIImage *)codeImage {
    
    NSString *title = [info valueForKey:@"title"];

    [self updateTableHeaderViewWithCodeString:code orImage:codeImage];
    self.codeHeaderView.titleLabel.text = title;
    
}


- (void)codeManager:(id<QDCodeManager>)codeManager failType:(QDMetroHeaderErrorType)type {
    [self updateTableHeaderViewWithErrorType:type];
}


#pragma mark - <QDScreenShotAlertViewDelegate>
- (void)qdScreenShotAlertViewWillDismiss:(QDScreenShotAlertView *)view {}


#pragma mark - <QDMetroErrorHeaderViewDelegate>
- (void)qdMetroErrorHeaderView:(QDMetroErrorHeaderView *)headerView handerButtonDidTap:(QDMetroHeaderErrorType)errorType {
    
    //TODO: 根据type进行操作
    switch (errorType) {
        //TODO:跳转蓝牙
        case QDMetroHeaderErrorTypeOutBluetooth:
            [RITLSystemSettingVisitor visitSystemSettingWithType:RITLSystemSettingTypeBluetooth]; break;
        //TODO:联系客服
        case QDMetroHeaderErrorTypeInBlacklist:
            RITLCall(self.servicePhone); break;
        //TODO:去登陆
        case QDMetroHeaderErrorTypeLoginStatus:
            [self checkLogin:^{ }]; break;
        case QDMetroHeaderErrorTypeNFC:
            [self switchQrcodeType]; break;
        //TODO:去绑定支付方式
        case QDMetroHeaderErrorTypeOutPayType:
            [self routerToPayTypeList]; break;
        //TODO:重新刷新
        case QDMetroHeaderErrorTypeNetFail:
            [self requestAllPayType]; break;
        //TODO: 默认支付方式
        case QDMetroHeaderErrorTypeOutDefaultChannel:
            [self showPayTypePickerView]; break;
        case QDMetroHeaderErrorTypeNone: break;
        default: break;
    }
}


#pragma mark - <UITableViewDataSource>


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.imageUrls.count == 0 ? 0 : 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    QDMetroCycleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"QDMetroCycleTableViewCell" forIndexPath:indexPath];
    
    __weak typeof(self) weakSelf = self;
    
    //进行配置
    cell.configCellIdentifierHandler = ^NSString * _Nonnull(SDCycleScrollView * _Nonnull cycleView, NSIndexPath * _Nonnull indexPath) {
        return weakSelf.isBoxs[indexPath.item].boolValue ? QDSDCycleHZCellKey : QDSDCycleNormalCellKey;
    };
    
    
    //进行设置值    
    cell.customHandler = ^(SDCycleScrollView * _Nonnull cycleView, UICollectionViewCell * _Nonnull cell, NSIndexPath * _Nonnull indexPath) {
        
        //如果是活动盒子
        if ([cell isKindOfClass:QDHDHZCycleCollectionViewCell.class]) {

            QDHDHZCycleCollectionViewCell *heziCell = (QDHDHZCycleCollectionViewCell *)cell;

            //重新设置代理
            heziCell.bannerView.delegate = self;
            //设置默认图片
            [heziCell.bannerView setPlaceholder:RITLColorFromIntRBG(100, 181, 116).ritl_image model:UIViewContentModeScaleAspectFill];
            //设置key以及属性
            [heziCell.bannerView setPositionKey:weakSelf.boxKeys[indexPath.item] properties:self.hzProperties]; return;
        }
        
        //如果是普通的
        SDCollectionViewCell *imageCell = (SDCollectionViewCell *)cell;
        imageCell.backgroundColor = RITLColorFromIntRBG(100, 181, 116);
        imageCell.contentView.backgroundColor = RITLColorFromIntRBG(100, 181, 116);
        imageCell.imageView.backgroundColor = RITLColorFromIntRBG(100, 181, 116);
        imageCell.imageView.contentMode = UIViewContentModeScaleAspectFill;
        imageCell.imageView.clipsToBounds = true;
    };
    
    // 选中
    cell.selectHandler = ^(SDCycleScrollView * _Nonnull cycleView, NSInteger index) {
        
        [QDUMEventManager eventObjcWithEvent:@"300"];
        NSLog(@"index = %@",@(index));
        [weakSelf pushToShareWebViewControllerWithUrl:weakSelf.webUrls[index] shareTitle:weakSelf.shareTitles[index] shareImageUrl:nil shareDesc:nil autoTitle:false title:@"详情" id:nil qdmetro:true];
    };
    
    //进行赋值
    cell.cycleView.imagePathsGroup = self.imageUrls;

    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return QDMetroCycleTableViewCellHeight();
}


#pragma mark - <QDCodePopOverTableViewDelegate>

- (void)codePopOverTableView:(QDCodePopOverTableView *)tableView didSelected:(NSString *)title index:(NSInteger)index {
    
    //消失
    [self.itemPopover dismiss];
    
    __weak typeof(self) weakSelf = self;
    
    //进行跳转
    if ([title isEqualToString:@"乘车码设置"]) {
        
        [self checkLogin:^{
            [weakSelf routerToCodeSetting];
        }]; return;
    }
    
    else if ([title isEqualToString:@"自助补站"]){
        
        [self checkLogin:^{
            [weakSelf routerToMetroSelfService];
        }]; return;
    }
    
    else if ([title isEqualToString:@"使用范围"]){
        [self routerToBusLines]; return;
    }
    
    NSLog(@"title = %@",title);
}


#pragma mark - 紧急公告

/// 请求紧急公告
- (void)requestUrgentNotices {
    
    [QDNetworkingManager requestUrgentNoticesWithComplete:^(BOOL hasNotice,NSArray<NSString *> * _Nonnull titles, NSArray<NSString *> * _Nonnull webUrls) {
       
        // 进行赋值
        self.notices = titles ?: @[];
        self.noticesUrls = webUrls ?: @[];
        self.noticeView.scrollable = [self noticeShouldScrollWithTitle:self.notices.ritl_safeFirstObject];
        
        //获得紧急公告
        if (!titles || titles.count == 0) {//如果不存在或者数量为0，进行隐藏
            
            [self.noticeView.marqueeView stop];
            
            [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            
                self.noticeView.ritl_height = 0;
                
            } completion:nil]; return;
        }
        
        self.noticeView.title = self.notices.firstObject;
        
        [self.noticeView.marqueeView run];
        [UIView animateWithDuration:0.1 delay:0 options:UIViewAnimationOptionCurveLinear animations:^{
            
            self.noticeView.ritl_height = 36;
            
        } completion:nil]; return;
    }];
}



//文字的宽度,用来限制是否滚动
- (BOOL)noticeShouldScrollWithTitle:(NSString *)title {
    
    if (!title) { return false; }
    
    // 限制的宽度
    CGFloat limitWidth = UIScreen.mainScreen.ritl_width - 42 - 67;
    // 文字的实际宽度
    CGFloat width = [[[NSAttributedString alloc] initWithString:title attributes:@{NSFontAttributeName: RITLRegularFont(14)}] boundingRectWithSize:CGSizeMake(10000, 100) options:NSStringDrawingUsesLineFragmentOrigin context:nil].size.width;
    // 结果
    return width > limitWidth;
}


#pragma mark - Lazy

- (QDPayTypeDefaultPickerView *)paytypePickView {
    
    if (!_paytypePickView) {
        
        _paytypePickView = QDPayTypeDefaultPickerView.new;
        [self bindingPayTypePickerAction];
    }
    
    return  _paytypePickView;
}


- (QDMetroErrorHeaderView *)errorHeaderView {
    if (!_errorHeaderView) {
        
        QDMetroErrorHeaderView *errorHeaderView = QDMetroErrorHeaderView.new;
        errorHeaderView.ritl_size = CGSizeMake(self.ritl_width, 330 + /*4*/ + QDErrorAddtionBottomDistance() + QDErrorAddtionTopDistance());
        errorHeaderView.imageView.backgroundColor = QDSColorTheme;
        errorHeaderView.delegate = self;
        
        _errorHeaderView = errorHeaderView;
    }
    return _errorHeaderView;
}


- (UIButton *)rightButton {
    if (!_rightButton) {
        
        UIButton *rightItem = ({
            
            UIButton *view = [UIButton new];
            view.adjustsImageWhenHighlighted = false;
            
            [view setImage:@"mc_more".ritl_image forState:UIControlStateNormal];
            [view setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
            [view addTarget:self action:@selector(rightButtonItemDidTap) forControlEvents:UIControlEventTouchUpInside];
            
            view;
        });
        
        _rightButton = rightItem;
    }
    return _rightButton;
}


- (QDMetroCodeSegmentBar *)segmentBar {
    if (!_segmentBar) {
        
        QDMetroCodeSegmentBar *segmentBar = QDMetroCodeSegmentBar.new;
        
        segmentBar = QDMetroCodeSegmentBar.new;
        segmentBar.backgroundColor = self.tableViewBackgroundColor;
        segmentBar.layer.borderColor = UIColor.whiteColor.CGColor;
        segmentBar.layer.borderWidth = 1;
        segmentBar.layer.cornerRadius = 4;
        segmentBar.clipsToBounds = true;
        
        __weak typeof(self) weakSelf = self;
        segmentBar.segmentBarClickHandler = ^(QDMetroCodeSegmentBar * _Nonnull segmentBar, NSInteger index) {
            
            weakSelf.isMetro = (index == 0); //更新标志位
            if (index == 0) {//地铁
                weakSelf.currentCodeManager = weakSelf.metroCodeManager; return;
            }
            weakSelf.currentCodeManager = weakSelf.busCodeManager;
        };
        
        _segmentBar = segmentBar;
    }
    return _segmentBar;
}


- (ASPopover *)itemPopover {
    if (!_itemPopover) {
        
        ASPopoverOption *option = ASPopoverOption.new;
        option.arrowSize = CGSizeMake(12, 4);
        option.offset = 12;
        option.sideEdge = 20;
        option.cornerRadius = 4;
        option.popoverType = ASPopoverTypeDown;
        option.blackOverlayColor = [UIColor.blackColor colorWithAlphaComponent:0.3];
        option.popoverColor = UIColor.whiteColor;
        option.animationIn = 0.4;
        option.animationOut = 0.3;
        option.initialSpringVelocity = 1;
        
        ASPopover *popOver = [[ASPopover alloc]initWithOption:option];
        
        _itemPopover = popOver;
    }
    return _itemPopover;
}


/// 模拟的导航栏
- (UIView *)titleView {
    
    if (!_titleView) {
        
        _titleView = ({
            
            UIView *view = [UIView new];
            view.layer.cornerRadius = 4;
            view.clipsToBounds = true;
            view.backgroundColor = RITLColorFromIntRBG(100, 181, 116);
            
            view;
        });
        
        //追加titleLabel
        [_titleView addSubview:self.segmentBar];
        [_titleView addSubview:self.rightButton];
        
        
        [self.segmentBar mas_makeConstraints:^(MASConstraintMaker *make) {
            make.width.mas_equalTo(200);
            make.height.mas_equalTo(36);
            make.centerX.offset(isSmallerScreen() ? -4 : 0 );
            make.bottom.inset(isSmallerScreen() ? 10 : 28);
        }];
        
        
        [self.rightButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.inset(20);
            make.height.width.mas_equalTo(44);
            make.bottom.inset(isSmallerScreen() ? 14 : 32);
            
        }];
    }
    return _titleView;
}

@end
